<?php
/*
 Author:F.Y
 Email: fy@yiyou.org
 Website:http://www.yiyou.org
 Date:2015-01-20
*/
require_once("kp.class.php");
require_once("config.php");

$kp = new kp(CONSUMER_KEY,CONSUMER_SECRET);

if (file_exists('./kp_oauth.php'))
$oauth = json_decode(file_get_contents('./kp_oauth.php'));//´Ԏļþא¶¡

if (!empty($oauth))
{
        $kp->oauth_token = $oauth->oauth_token;
        $kp->oauth_token_secret = $oauth->oauth_token_secret;
}
else
{
   die ("Please run oauth.php on web and get access_token.");
}

$remotedir=array();
$localdir=array();

$res=$kp->dir(BACKUP_DIR);
#$res=$kp->dir('/');
#print_r($kp);exit;
if($res ==''){
    echo "BACKUP_DIR not exists!\n";
	echo $kp->md(BACKUP_DIR);
}else{
	foreach($res as $f){
		array_push($remotedir,$f->name);
	}
}
//print_r($remotedir);
echo "List remote dir done.\n";

$d = dir(LOCAL_DIR);
echo "Local Backup Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
	if($entry !='.' && $entry != '..')
		array_push($localdir,$entry);
}
$d->close();
//print_r($localdir);
echo "List local dir done.\n";

// get del  remote file 
$del=array_diff($remotedir,$localdir);
//echo "del file now ...\n";
foreach ($del as $d){
	$file=BACKUP_DIR.'/'.$d;
#	echo "del $file \n";
#	$kp->rm($file);
}
//print_r($del);

//get upload file
$add=array_diff($localdir,$remotedir);
//echo "upload file now ....\n";
//print_r($add);
foreach ($add as $a){
	$file=LOCAL_DIR.'/'.$a;
	echo "upload $file\n";

	$i=3;
	do{
		$ret=$kp->upload(BACKUP_DIR,$file,false);
		if ($ret==false){
			echo "fail:".$kp->errstr."\n try $i time(s) ...\n";
			$i--;
		}else{
			echo "ok:ID:".$ret."\n";
			$i=0;
		}
	}while($i>0);
}